<template>
  <el-form-item
    :rules="item.rule"
    :label="item.label"
    :prop="item.prop"
    ref="formItem"
    class="selectCustomizeCom"
  >
    <el-popover
      placement="bottom-start"
      width="400"
      popper-class="popoverCss"
      trigger="click"
      ref="modal"
      @show="showCallback"
      @hide="hideCallback"
      v-model="hide"
    >
      <div class="infinite-list-wrapper">
        <div
          :is="activeAll"
          v-model="checkAll"
          :indeterminate="isIndeterminate"
          @change="handleCheckAllChange"
          class="header"
          v-if="item.title"
        >
          <div :class="item.title ? 'list-top' : ''">
            <span>{{ item.title }}</span
            ><span v-show="item.info">{{ item.info }}</span>
          </div>
        </div>
        <div
          :is="activeContent"
          v-model="selectedData"
          @change="handleCheckedCitiesChange"
          ref="myScrollbar"
          class="myScrollbar"
          :style="{ height: height }"
          v-el-table-infinite-scroll="load"
        >
          <ul class="list">
            <li
              v-for="(_item, index) in item.children"
              :key="index"
              class="list-item"
              :class="[
                item.multiple ? 'multipleCss' : 'noMultiple',
                _item.value == selectedData ? 'active' : ''
              ]"
              @click="!item.multiple && singleClick(_item)"
              @mouseenter="visibleTooltipChange($event)"
            >
              <!--下拉列表的悬浮消息位-->
              <el-tooltip
                :content="
                  _item.info ? `${_item.label}（${_item.info}）` : _item.label
                "
                placement="top"
                :disabled="!showTooltip"
              >
                <div slot="content" v-if="_item.info">
                  {{ _item.label }}<br />{{ _item.info }}
                </div>
                <div slot="content" v-else>{{ _item.label }}</div>
                <div :is="active" :label="_item.value" :key="_item.value">
                  <div class="title">{{ _item.label }}</div>
                  <div class="info">{{ _item.info }}</div>
                </div>
              </el-tooltip>
            </li>
          </ul>
          <p v-if="loading && !item.noMore">加载中...</p>
          <!-- <p v-if="item.noMore">没有更多了</p> -->
        </div>
      </div>
      <!--分割-->
      <el-button
        v-if="item.disabled"
        slot="reference"
        class="select-customize-btn"
        disabled
      >
        <el-input placeholder="搜索关键词" v-model="input" disabled> </el-input>
      </el-button>
      <el-button v-else slot="reference" class="select-customize-btn">
        <div class="my-select">
          <div class="my-select__tip">
            <span
              v-if="showSelectedButton"
              v-show="txt"
              class="my-tip"
              :class="{ 'my-tip-single': !item.multiple }"
            >
              <span>
                <!--已选N项的悬浮消息位-->
                <el-tooltip placement="top" :disabled="!item.multiple">
                  <div slot="content">
                    <span v-for="(label, index) in tipInfos" :key="index">
                      {{ label }}<br />
                    </span>
                  </div>
                  <span class="my-tip-txt" :title="txt">{{ txt }}</span>
                </el-tooltip>
                <span
                  class="my-tip-icon"
                  v-if="item.clearable === undefined ? true : item.clearable"
                  @click.stop.prevent="deleteSelect"
                >
                  <i
                    class="el-select__caret el-input__icon el-icon-circle-close hidden"
                  ></i
                ></span>
              </span>
            </span>
            <input
              v-if="item.multiple"
              type="text"
              @keydown="debounceFun"
              placeholder="搜索关键词"
              autocomplete="off"
              :class="['el-select__input', { 'left-5': txt }]"
              style="flex-grow: 1; width: 0.0961538%; max-width: 198px;"
              v-model="searchInput"
            />
          </div>
          <div class="my-input--suffix">
            <input
              tabindex="-1"
              type="text"
              readonly="readonly"
              autocomplete="off"
              placeholder=""
              class="my-input__inner"
              :class="showPopover ? 'active' : ''"
            />
            <span class="my-input__icon">
              <span class="my-input__icon-inner">
                <i
                  class="my-select__caret my-input__icon el-icon-arrow-up "
                  :class="showPopover ? 'is-reverse' : ''"
                ></i>
              </span>
            </span>
          </div>
        </div>
      </el-button>
    </el-popover>
  </el-form-item>
</template>
<script>
import Scrollbar from "../../utils/Scrollbar";

export default {
  name: "selectCustomizeCom",
  props: {
    item: {
      type: Object,
      default: () => {
        return {};
      }
    },
    formData: {
      type: Object,
      default: () => {
        return {};
      }
    },
    height: {
      type: String,
      default: () => {
        return "200px";
      }
    },
    isReset: {
      type: Boolean,
      default: () => {
        return false;
      }
    }
  },
  data() {
    return {
      input: "",
      showDelete: false,
      txt: "",
      loading: false,
      checkAll: false,
      isIndeterminate: false,
      debounceFun: "",
      searchInput: "",
      showPopover: false,
      selectedData: "", // "" / []
      scrollbar: "",
      isDeleted: false,
      hide: false,
      showTooltip: false
    };
  },
  directives: {
    "el-table-infinite-scroll": {
      bind(el, binding) {
        const selectWrap = el;
        selectWrap.addEventListener("scroll", function() {
          let sign = 100;
          const scrollDistance =
            this.scrollHeight - this.scrollTop - this.clientHeight;
          if (scrollDistance <= sign) {
            binding.value();
          }
        });
      }
    }
  },
  computed: {
    showSelectedButton() {
      return (
        typeof this.item.showSelectedButton === "undefined" ||
        this.item.showSelectedButton
      );
    },
    disabled() {
      return false; //this.loading || this.item.noMore
    },
    activeAll() {
      // 保留全选的代码
      return this.item.multiple
        ? this.item.showCheckAll === false
          ? "div"
          : "el-checkbox"
        : "div";
    },
    active() {
      return this.item.multiple ? "el-checkbox" : "div";
    },
    activeContent() {
      return this.item.multiple ? "el-checkbox-group" : "div";
    },
    tipInfos() {
      if (!this.item.multiple) return "";
      const allDatas = this.item.children || [];
      const selectedData = this.selectedData || [];
      const checkLabels = _.filter(allDatas, item => {
        return selectedData.find(i => i === item.value);
      }).map(item => item.label);
      return checkLabels;
    }
  },
  watch: {
    "item.labelValue": {
      deep: true,
      handler(val) {
        val && (this.txt = val);
      }
    },
    isReset(newVal, oldVal) {
      if (newVal) {
        // 重置数据
        this.selectedData = this.formData[this.item.prop];
        this.searchInput = "";
        this.txt = "";
        this.item.labelValue = "";
      }
    },

    formData(newVal, oldVal) {
      this.selectedData = newVal[this.item.prop];
    },
    selectedData(newVal, oldVal) {
      if (newVal === oldVal) {
        return;
      }
      this.$set(this.formData, this.item.prop, newVal);
      if (
        !oldVal &&
        !this.isDeleted &&
        !this.item.multiple &&
        this.item.labelValue
      ) {
        // 单选：首次进入页面,如果labelValue有值优先获取labelValue的值
        this.txt = this.item.labelValue;
        return;
      }
      if (newVal) {
        if (!this.item.multiple) {
          // 单选
          const data = this.item.children.find(res => res.value === newVal);
          this.txt = data ? data.label : "";
        } else {
          // console.log("newVal", newVal);
          // 多选用户点击重置
          let checkedCount = newVal ? newVal.length : 0;
          this.checkAll =
            this.item.children &&
            checkedCount === this.item.children.length &&
            this.item.children.length !== 0;
          this.isIndeterminate =
            checkedCount > 0 &&
            this.item.children &&
            checkedCount < this.item.children.length;
          this.txt =
            newVal && newVal.length > 0 ? "已选" + checkedCount + "项" : "";
        }
      } else {
        this.txt = "";
      }
    }
  },
  methods: {
    visibleTooltipChange(event) {
      const ev = event.target.querySelector(".title");
      const thisWidth = ev.clientWidth;
      const textWidth = ev.scrollWidth;
      this.showTooltip = textWidth > thisWidth;
    },
    deleteSelect() {
      this.isDeleted = true;
      this.selectedData = this.item.multiple ? [] : "";
      // 清空值时也清空txt
      this.txt = this.selectedData ? this.txt : "";
      this.$refs.modal.doClose();
      this.item.change && this.item.change(this.selectedData, this.txt);
    },
    showCallback() {
      this.showPopover = true;
      this.searching();
    },
    hideCallback() {
      this.showPopover = false;
      this.item.change && this.item.change(this.selectedData, this.txt);
    },
    search() {
      if (this.$refs.modal) {
        this.$refs.modal.doShow();
      }
      this.searching();
    },
    searching() {
      this.item.searchChangeCallback &&
        this.item.searchChangeCallback(this.searchInput);
    },
    async load() {
      if (this.loading) return;
      console.log("下一页noMore", this.item.noMore);
      if (this.item.multiple) {
        let checkedCount = this.selectedData.length;
        this.checkAll =
          checkedCount === this.item.children.length &&
          this.item.children.length !== 0;
        this.isIndeterminate =
          checkedCount > 0 && checkedCount < this.item.children.length;
      }

      if (!this.item.noMore) {
        this.loading = true;
        this.item.searchNextCallback && (await this.item.searchNextCallback());
        this.loading = false;
      }
    },
    singleClick(item) {
      if (!this.item.multiple) {
        this.$refs.modal.doClose();
        this.selectedData = item.value;
        this.item.onChange && this.item.onChange(this.selectedData, item);
      }
      this.$nextTick(() => {
        this.searchInput = "";
        this.$refs.formItem.clearValidate();
      });
    },
    handleCheckAllChange(val) {
      if (!this.item.multiple) {
        return;
      }
      const allList = this.item.children;
      const selectedData = (this.selectedData = val
        ? allList.map(res => res.value)
        : []);
      this.item.onChange && this.item.onChange(selectedData, allList);
      this.$nextTick(() => {
        this.searchInput = "";
        this.$refs.formItem.clearValidate();
      });
    },
    handleCheckedCitiesChange(value) {
      if (!this.item.multiple) {
        return;
      }
      this.selectedData = value;
      const selectedList = this.item.children.filter(child =>
        value.find(v => v == child.value)
      );
      this.item.onChange && this.item.onChange(value, selectedList);
      this.$nextTick(() => {
        this.$refs.formItem.clearValidate();
      });
    },
    keyupFun(e) {
      if (e.keyCode === 27) {
        this.hide = false;
      }
    }
  },
  created() {
    this.selectedData = this.item.multiple
      ? this.formData[this.item.prop] || []
      : this.formData[this.item.prop];
    this.item.search = this.searching.bind(this);
  },
  mounted() {
    this.debounceFun = _.debounce(this.search, 1000);
    let scrollbar = (this.scrollbar = this.scrollbar = this.item.multiple
      ? new Scrollbar(this.$refs.myScrollbar.$el)
      : new Scrollbar(this.$refs.myScrollbar));
    scrollbar.show();
    this.item.clearable =
      this.item.clearable === undefined ? true : this.item.clearable;
    document.addEventListener("keyup", this.keyupFun);
  },
  updated() {
    if (
      !this.txt &&
      !this.isDeleted &&
      !this.item.multiple &&
      this.item.labelValue
    ) {
      this.txt = this.item.labelValue;
      return;
    }
    this.scrollbar.show();
    this.$nextTick(() => {
      this.scrollbar.resize();
    }, 100);
  },
  destroyed() {
    document.removeEventListener("keyup", this.keyupFun);
  }
};
</script>

<style scoped lang="scss">
/**只能在最外层*/
::v-deep.el-popover {
  padding: 10px !important;
}

::v-deep.popoverCss {
  padding: 10px !important;
}

.selectCustomizeCom {
  ::v-deep.el-form-item__content {
    > span {
      width: 100%;
    }
  }

  .my-select {
    width: 100%;
    display: inline-block;
    position: relative;

    ::v-deep.el-select__input.left-5 {
      margin-left: 5px;
    }
  }
  .my-select__tip {
    width: 100%;
    max-width: 70%;
    position: absolute;
    line-height: normal;
    white-space: normal;
    z-index: 1;
    top: 50%;
    transform: translateY(-50%);
    display: flex;
    align-items: center;
    flex-wrap: wrap;
  }
  .my-input__icon {
    position: absolute;
    height: 100%;
    right: 0;
    top: 0;
    text-align: center;
    color: #c0c4cc;
    transition: all 0.3s;
    pointer-events: none;
    width: 25px;
    line-height: 32px;
    height: 100%;
    text-align: center;
  }
  .my-input__icon-inner {
    pointer-events: all;
  }

  .my-input__icon.is-reverse {
    transform: rotate(0deg);
  }

  .el-icon-arrow-up:before {
    content: "\e6e1";
  }

  .my-input__icon:after {
    content: "";
    height: 100%;
    width: 0;
    display: inline-block;
    vertical-align: middle;
  }
  .my-input__inner {
    padding-right: 30px;
    cursor: pointer;
    -webkit-appearance: none;
    background-color: #fff;
    background-image: none;
    border-radius: 4px;
    border: 1px solid #cecece;
    box-sizing: border-box;
    color: #606266;
    display: inline-block;
    font-size: inherit;
    height: 40px;
    line-height: 32px;
    outline: none;
    padding: 0 15px;
    transition: border-color 0.2s cubic-bezier(0.645, 0.045, 0.355, 1);
    width: 100%;
  }

  .my-input__inner.active {
    border: 1px solid #1b65b9;
  }

  .my-select__caret {
    color: #c0c4cc;
    font-size: 14px;
    transition: transform 0.3s;
    transform: rotate(180deg);
    cursor: pointer;
  }

  .hidden {
    display: none;
  }
  .my-tip {
    min-width: 100px;

    &:hover {
      .my-tip-icon > i {
        display: block;
      }
    }
    > span:first-child {
      display: flex;
      align-items: center;
      height: 25px;
      margin-left: 4px;

      &:hover {
        color: #606266;
        background-color: #f0f2f5;
      }
    }

    .my-tip-txt {
      flex: 1;
      padding-left: 12px;
      width: 70%;
      text-overflow: ellipsis;
      white-space: nowrap;
      overflow: hidden;
      text-align: left;
    }

    .my-tip-icon {
      width: 25px;
      padding-top: 2px;
    }
  }
  .select-customize-btn {
    margin: 0;
    padding: 0;
    height: 32px;
    width: 100%;
    border: 0;
    ::-webkit-input-placeholder {
      /* WebKit browsers */
      color: #c0c4cc;
    }

    ::-moz-placeholder {
      /* Mozilla Firefox 19+ */
      color: #c0c4cc;
    }

    :-ms-input-placeholder {
      /* Internet Explorer 10+ */
      color: #c0c4cc;
    }
  }
  .select-customize-btn:hover,
  .select-customize-btn:focus {
    color: #606266;
  }
  .my-tip-single {
    width: 97%;

    .my-tip-txt {
      padding-left: 10px;
    }
  }
}

//下拉选中
.infinite-list-wrapper {
  text-align: center;

  .list-top {
    height: 40px;
    text-align: left;
    color: #303133;

    span {
      color: #606266;
    }
  }

  .list {
    padding: 0;
    margin: 0;
    list-style: none;
  }

  .list-item {
    display: flex;
    flex-flow: column;
    align-items: center;
    justify-content: left;
    width: 100%;
    height: 50px;
    background: #ffffff;
    color: #ff8484;
    padding: 0 10px;
    border-bottom: 1px solid #e4e7ed;
    .title,
    .info {
      font-size: 13px;
      font-family: "Microsoft YaHei", "微软雅黑", Arial, sans-serif,
        "Helvetica Neue", Helvetica, "PingFang SC", "Hiragino Sans GB";
      font-weight: 400;
      line-height: 18px;
      white-space: nowrap;
      word-break: break-all;
      overflow: hidden;
      text-overflow: ellipsis;
    }
    .title {
      color: rgba(48, 49, 51, 1);
    }
    .info {
      color: rgba(144, 147, 153, 1);
    }

    > div {
      width: 100%;
      height: 18px;
      font-size: 13px;
      font-family: "Microsoft YaHei", "微软雅黑", Arial, sans-serif,
        "Helvetica Neue", Helvetica, "PingFang SC", "Hiragino Sans GB";
      font-weight: 400;
      color: rgba(48, 49, 51, 1);
      line-height: 18px;
      text-align: left;
    }
  }

  .list-item:hover {
    background-color: #f5f7fa;
  }

  .list-item.noMultiple {
    > div {
      height: 100%;
      display: flex;
      flex-flow: column;
      -webkit-box-align: center;
      justify-content: center;
    }
  }

  .list-item.noMultiple.active {
    background-color: #f5f7fa;
    > div {
      color: #409eff;
      font-weight: 700;
    }
  }
  .list-item.multipleCss {
    label {
      width: 100%;
      height: 100%;
      text-align: left;
      display: flex;
      align-items: center;
      ::v-deep.el-checkbox__label {
        width: calc(100% - 20px);
      }
    }
  }

  p {
    font-size: 14px;
    color: #5e6d82;
    line-height: 1.5em;
  }
}

.myScrollbar {
  overflow: auto;
}

.header {
  width: 100%;
  height: 40px;
  line-height: 40px;
  text-align: left;
  padding: 0 10px;
  background: rgba(240, 242, 245, 1);
}

::v-deep .el-form-item.is-error .my-input__inner {
  border-color: #f56c6c;
}
</style>
